<template>
    <div>
        <List v-model="loading" @load="loadMore" :finished="finished" finished-text="没有更多了" :offset="100">
            <CellGroup v-for="item in newsList" :key="item.id">
                <Cell :title="item.title" :icon="item.image" :label=" item.focus_date"
                    :to="{ name: 'NewsInfo', params: { type: item.image2 ? 'photo' : 'news', id: item.id } }"/>
            </CellGroup>
        </List>
    </div>
</template>

<script>
import { List, Cell, CellGroup  } from 'vant';
import { getNewsList } from '@/services';

export default {
    name: 'NewsList',
    components: { List, Cell, CellGroup },
    data() {
        return {
            newsList: [],
            page: 1,
            total: 0,
            loading: true,
            finished: false
        };
    },
    methods: {
        // 上拉加载更多
        loadMore() {
            // 判断是否还有数据
            if (this.newsList.length >= this.total) {
                this.finished = true;
                return;
            } 
            getNewsList(this.page + 1)
                .then(({ newsList, page }) => {
                    newsList.forEach(item => this.newsList.push(item));
                    this.page = page;
                    this.loading = false;
                })
                .catch(err => {
                    console.error(`第 ${this.page + 1} 页新闻数据获取失败`, err.message);
                    this.loading = false;
                });
        }
    },
    created() {
        getNewsList()
            .then(({ newsList, page, total }) => {
                this.newsList = newsList;
                this.page = page;
                this.total = total;
                this.loading = false;
            })
            .catch(err => {
                console.error('新闻数据获取失败', err.message);
                this.loading = false;
            });
    }
};
</script>

<style lang="less" scoped>
    @cellHeight: 70px;

    .van-cell {
        height: 90px;
        box-sizing: border-box;
        font-family: PingFang SC,Arial,\\5FAE\8F6F\96C5\9ED1,\\5B8B\4F53,simsun,sans-serif;
        .van-cell__left-icon {
            width: calc(@cellHeight * (266 / 150));
            height: @cellHeight;
            margin-right: 10px;
            overflow: hidden;
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
        .van-cell__title {
            position: relative;
            & > span {
                overflow: hidden;
                line-height: 1.5rem;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                display: -webkit-box;
                font-size: 16px;
            }
            .van-cell__label {
                position: absolute;
                bottom: -4px;
            }
        }
    }
</style>